package by.alex.dzeshko.facebooksuperclient.models.common;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;
import by.alex.dzeshko.facebooksuperclient.ContextHolder;
import by.alex.dzeshko.facebooksuperclient.R;

public class JSONModel {
	
private static final String LOG_TAG = "JSONModel";

Context mContext = ContextHolder.getInstance().getContext();

protected JSONObject jo;
	
	public JSONModel(JSONObject jsonObject) {
		jo = jsonObject;
	}
	
	public JSONModel(String jsonString) {
		try {
			jo = new JSONObject(jsonString);
		} catch (JSONException e) {
			Log.e(LOG_TAG, e.toString());
		}
	}
	
	public JSONModel() {
		jo = new JSONObject();
	}
	
	public String getString(String key) {
		if (jo.isNull(key)) {
			return null;
		} try {
			if(jo.has(key)){
			return jo.getString(key);
			}
		} catch (JSONException e) {
			Log.e(LOG_TAG, e.toString());
		}
		return null;
	}
	
	public String getString(int res) {
		return getString(mContext.getString(res));
	}
	protected String getSecondLevelString(String firstKey, String secondKey) {
		if (jo.isNull(firstKey)) {
			return null;
		}
		try {
			if(jo.has(firstKey)){
			return jo.getJSONObject(firstKey).getString(secondKey);
			}
		} catch (JSONException e) {
			Log.e(LOG_TAG, e.toString());
		}
		return null;
	}
	
	protected int getInt(String key) {
		if (jo.isNull(key)) {
			return -1;
		}
		try {
			if(jo.has(key)){
			return jo.getInt(key);
			}
		} catch (JSONException e) {
			Log.e(LOG_TAG, e.toString());
		}
		return -1;
	}
	
	protected Long getLong(String key) {
		if (jo.isNull(key)) {
			return null;
		}
		try {
			if(jo.has(key)){
			return jo.getLong(key);
			}
		} catch (JSONException e) {
			Log.e(LOG_TAG, e.toString());
		}
		return null;
	}

	protected int getSecondLevelInt(String firstKey, String secondKey) {
		if (jo.isNull(firstKey)) {
			return -1;
		}
		try {
			if(jo.has(firstKey)){
			return jo.getJSONObject(firstKey).getInt(secondKey);
			}
		} catch (JSONException e) {
			Log.e(LOG_TAG, e.toString());
		}
		return -1;
	}
	
	protected JSONObject getValueFromArray(String object, String objectKey, String requiredValue){
		if(object==null || requiredValue==null) return null;
		
		if (jo.isNull(object)) {
			return null;
		}
		JSONObject value=null;
		try {
			JSONArray ja = jo.getJSONArray(object);
			for(int i = 0; i<ja.length(); i++){
				JSONObject temp = ja.getJSONObject(i);
				if(temp.getString(objectKey).equals(requiredValue)){
					value = temp;
					return value;
				}
			}
		} catch (JSONException e) {
			Log.e(LOG_TAG, e.toString());
		}
		return null;
		
	}
	
}
